package com.lijian.community.controller;

import com.lijian.community.dto.CommentAddDTO;
import com.lijian.community.dto.CommentDTO;
import com.lijian.community.dto.ResultDTO;
import com.lijian.community.enums.CommentTypeEnum;
import com.lijian.community.exception.CustomizeErrorCode;
import com.lijian.community.model.Comment;
import com.lijian.community.model.User;
import com.lijian.community.service.CommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
public class CommentController {

    @Autowired
    private CommentService commentService;

    @PostMapping("/comment")
    public ResultDTO comment(@RequestBody CommentAddDTO commentAddDTO,
                          HttpServletRequest request){

        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            return ResultDTO.error(CustomizeErrorCode.NO_LOGIN);
        }
        if(commentAddDTO == null || StringUtils.isBlank(commentAddDTO.getContent())){
            return null;
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentAddDTO, comment);
        comment.setQuestionId(commentAddDTO.getQuestionId());
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        comment.setUserId(user.getId());
        commentService.addComment(comment, user);
        //更新一级评论的评论数量
        commentService.incCommentCount(comment.getQuestionId());
        return ResultDTO.ok();
    }

    @GetMapping("/comment/{id}")
    public ResultDTO<List<CommentDTO>> comments(@PathVariable Integer id){
        List<CommentDTO> commentDTOList = commentService.findListTargetById(id, CommentTypeEnum.COMMENT);
        return ResultDTO.ok(commentDTOList);
    }
}
